<?php

namespace app\admin\controller\issuer;
use app\common\controller\Backend;
use think\Db;
use think\Loader;

/**
 * 发行记录
 *
 * @icon fa fa-file-text-o
 */
class Publish extends Backend
{
    /**
     * School模型对象
     */
    protected $searchFields = '';
    protected $model = null;
    protected $put_model = null;
    protected $group_id = null;
    protected $noNeedRight = ['see_img','see_invoice'];
    protected $isSuperAdmin = false;
    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\issuer\Publish();
        $this->put_model = new \app\admin\model\admin\PutCard();
        //是否超级管理员
        $this->isSuperAdmin = $this->auth->isSuperAdmin();
        $this->group_id = $this->auth->getGroupIds()[0];
    }

    /**
     * 发行记录
     */
    public function index()
    {
        $request = $this->request->request();
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $where_new =[];
            $year = isset($request['year'])?$request['year']:'';
            $distributor_type = isset($request['distributor_type'])?$request['distributor_type']:'';
            $group_id = isset($request['group_id'])?$request['group_id']:0;
            $admin_id = isset($request['admin_id'])?$request['admin_id']:0;
            $distributor = isset($request['distributor'])?$request['distributor']:'';
            $city = isset($request['city'])?$request['city']:'全部';
            $audit_status = isset($request['audit_status'])?$request['audit_status']:'全部';
            $province = isset($request['province'])?$request['province']:'全国';
            $begin_time = isset($request['begin_time'])?$request['begin_time']:'';
            $end_time = isset($request['end_time'])?$request['end_time']:'';
            if ($year) $where_new['year'] = $year;
            if ($distributor) $where_new['b.distributor_name'] = ['like','%'.$distributor.'%'];
            if ($distributor_type) $where_new['b.distributor_type'] = $distributor_type;
            if ($audit_status != '全部') $where_new['a.audit_status'] = $audit_status;
            if ($province != '全国') $where_new['a.province'] = $province;
            if ($city != '全部') $where_new['a.city'] = $city;
            $where_card_log = $where_card = $where_new;
            if ($begin_time) $where_card_log['l.create_time'] = $where_card['l.create_time'] = $where_new['a.put_time'] = ['between',[$begin_time,$end_time]];
            if($this->group_id >2){
                $where_card_log['l.admin_id']  = $where_card['a.admin_id']  =   $where_new['admin_id'] = $this->auth->id;
            }

            $total = $this->model
                ->alias('a')
                ->field('a.*,b.distributor_name,b.distributor_type')
                ->join('cd_admin b','a.distributor_id = b.id','left')
                ->where($where)
                ->where($where_new)
                ->count();
            $list =  $this->model
                ->alias('a')
                ->field('a.*,b.distributor_name,b.distributor_type')
                ->join('cd_admin b','a.distributor_id = b.id','left')
                ->where($where_new)
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
//            $have_total = Db::name('card_log')
//                ->alias('l')
//                ->join('cd_admin b','l.distributor_id = b.id','left')
//                ->join('card_put_info a','l.distributor_id = a.id','right')
//                ->where($where)
//                ->where(['is_activate'=>1])
//                ->where($where_card)
//                ->count();
//            echo Db::name('card_log')->getLastSql();
            unset($where_card['a.audit_status']);
//            if ($this->auth->id > 1) {
//                $group_info = Db::name('ca_auth_group')->where(['status' => 'normal'])->select();
//                $child_group = getAllChild($group_info, $this->group_id);
//                array_push($child_group, $this->group_id);
//                $uid_arr = Db::name('ca_auth_group_access')
//                    ->alias('ac')
//                    ->join('ca_admin a', 'a.id =ac.uid', 'right')
//                    ->where(['group_id' => ['in', $child_group], 'status' => 'normal'])
//                    ->column('uid');
//                //  $user_id_arr = Db::name('ca_admin')->where(['id'=>['in',$uid_arr],'status'=>'normal'])->column('id');
//                 $where_card['l.admin_id'] = ['in', $uid_arr];
//                // var_dump($where_new['creater_id']);
//            }
            if($this->auth->id>1){
                $where_card_log['l.distributor_id'] = ['>',1];
            }
            $card_total = Db::name('card_log')
                ->alias('l')
                ->join('cd_admin b','l.distributor_id = b.id','left')
                ->join('card_put_info a','l.distributor_id = a.id','left')
                ->where($where)
                ->where($where_card_log)
                ->count();
           // echo Db::name('card_log')->getLastSql();
            $no_total = Db::name('card_log')
                ->alias('l')
                ->join('cd_admin b','l.distributor_id = b.id','left')
                ->join('card_put_info a','l.distributor_id = a.id','left')
                ->where($where)
                ->where(['is_activate'=>0])
                ->where($where_card_log)
                ->count();
            $have_total = $card_total - $no_total;
            $result = array("total" => $total, "rows" => $list,"card_total"=>$card_total,"have_active" => $have_total,"no_active" => $no_total,
                "sql"=>Db::name('card_put_info')->getLastSql()
            );
            foreach ($list as $w=>&$v){
                $v['new_address'] = $v['province'].'-'.$v['city'];
                $v['put_price'] = $v['put_price']/100;
                $num = Db::name('card_log')->where(['card_type'=>0,'put_id'=>$v['id']])->count('id');
                $v['activate_num'] = Db::name('card_log')->where(['is_activate'=>1,'put_id'=>$v['id']])->count('id');
                $v['put_amount'] = $v['put_price']*$num;
            }

            return json($result);
        }

        $this->assign('province', get_pro());
        $this->assign('city', []);
        return $this->view->fetch();
    }

    public function make_invoice($ids = null){
        if (empty($ids)) exit('参数错误');
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                try {
                    $params['invoice_image']=str_replace('?x-oss-process=style/gkzzd','',$params['invoice_image']);
                    $params['create_time']=time();
                    $invoice_id=Db::name('card_invoice_info')->insertGetId($params);
                    $result=Db::name('card_put_info')->where(['id'=>$ids])->update(['invoice_id'=>$invoice_id]);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error(Db::name('card_put_info')->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }


        $this->view->assign('ids', $ids);
        return $this->view->fetch();
    }
    /**
     * 审核
     * @return string|\think\response\Json
     */
    public function see_img($ids=null){  //审核
     //   $type = input('type');
        // var_dump($type);
        $row = $this->put_model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        // var_dump($row);
        $arr_img = explode(',',$row['put_image']);
        foreach ($arr_img as $w=>&$v){
            $v = 'https://fjgk-file.oss-cn-hangzhou.aliyuncs.com/'.$v;
        }

     //   $this->view->assign("type", $type);
        $this->view->assign("row", $row);
        $this->view->assign("arr_img", $arr_img);
        $this->view->assign("sh_id", $ids);
        return $this->view->fetch();
    }


    public function see_invoice($ids = null){
        if (empty($ids)) exit('参数错误');
        $put_info = Db::name('card_put_info')->where(['id'=>$ids])->find();
        $invoice_info = Db::name('card_invoice_info')->where(['id'=>$put_info['invoice_id']])->find();
        $invoice_info['invoice_image'] = 'https://fjgk-file.oss-cn-hangzhou.aliyuncs.com/'.$invoice_info['invoice_image'];
        $this->view->assign('ids', $ids);
        $this->view->assign('invoice_info', $invoice_info);
        return $this->view->fetch();
    }
}
